<template>
  <div v-loading="isLoading" class="my-container">
    <!-- paper列表 -->
    <div v-if="paperList.isShow" class="my-card">
      <div class="flex-row">
        <el-checkbox v-model="paperList.onlyWatchMyself" @change="onPostGetPaper">只看我的</el-checkbox>
      </div>
      <el-table :data="paperList.tableData" border style="width: 100%;">
        <el-table-column sortable prop="create_time" label="上传时间" />
        <el-table-column sortable prop="paper_name" label="试卷标题" />
        <el-table-column sortable prop="paper_author" label="创建人" />
        <el-table-column label="操作" width="192">
          <template slot-scope="{ row }">
            <el-button-group>
              <el-button type="primary" icon="el-icon-view" @click="onhandlePaperClick(row)" />
              <el-button type="primary" icon="el-icon-edit" @click="onhandleUpdataClick(row)" />
              <el-button type="primary" icon="el-icon-delete" @click="checkOnDelete(row)" />
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 修改试卷 -->
    <div v-if="updataPaper.isShow">
      <div class="my-card">
        <el-page-header
          style="margin:0 0 24px 0"
          :content="'修改 '+
            (paperList.selectedPaperName.length > 32 ? paperList.selectedPaperName.slice(0, 31) + ' ...' : paperList.selectedPaperName)
          "
          @back="goBack"
        />

        <div class="flex-row">

          <el-button v-waves type="primary" icon="el-icon-plus" @click="beforeAddRow">
            添加
          </el-button>
          <el-button v-waves type="primary" icon="el-icon-download" @click="showDialog.downloadTableDialog = true">
            导出
          </el-button>
          <el-button v-waves type="primary" plain @click="resetIndexOfTable"> 重整序号 </el-button>
          <el-button v-waves type="primary" icon="el-icon-refresh" @click="showDialog.updataMyPaper = true">
            更新到数据库
          </el-button>
          <div style="flex: 1" />
          <el-button v-waves style="margin-left: 60px" type="warning" icon="el-icon-edit-outline" @click="beforAlterRow">
            编辑
          </el-button>
          <el-button v-waves type="danger" icon="el-icon-close" @click="showDialog.deleteRowsDialog=true"> 删除 </el-button>

        </div>
      </div>
      <div class="my-card">
        <!-- 操作的表格 -->
        <el-table :row-class-name="tableRowClassName" :data="updataPaper.tableData" max-height="580" border highlight-current-row style="width: 100%; margin-top: 20px" @row-click="onRowClick">
          <el-table-column v-for="item of updataPaper.tableHeader" :key="item.prop" :width="item.width" :prop="item.prop" :label="item.label" />
        </el-table>
      </div>
    </div>
    <!-- question列表 -->
    <div v-if="questionList.isShow">
      <!-- 学生界面预览控制栏 -->
      <div class="my-card">
        <el-page-header
          style="margin:0 0 24px 0"
          :content="
            paperList.selectedPaperName.length > 32 ? paperList.selectedPaperName.slice(0, 31) + ' ...' : paperList.selectedPaperName
          "
          @back="goBack"
        />
        <div class="flex-row">
          <span style="font-size:18px;margin-right:48px;">学生考试界面预览：</span>
          <div style="margin-right:24px;">
            <span>答题模式：</span>
            <el-radio-group v-model="questionList.DTMS">
              <el-radio-button label="整卷" />
              <el-radio-button label="单题" />
            </el-radio-group>
          </div>
          <div>
            <span>组卷形式：</span>
            <el-radio-group v-model="questionList.ZJXS" @change="questionInit">
              <el-radio-button label="顺序" />
              <el-radio-button label="乱序" />
            </el-radio-group>
          </div>
          <el-checkbox v-model="singleQuestion.isJiShi" style="margin-left:10px">计时</el-checkbox>
          <div>
            <el-checkbox v-if="questionList.DTMS === '单题'" v-model="singleQuestion.canNotPrevious" style="margin-left:10px">不允许后退</el-checkbox>
          </div>
        </div>
      </div>
      <!-- 整卷显示 -->
      <div v-if="questionList.DTMS === '整卷'" class="stu-card flex-column-center">
        <div class="flex-row" style="justify-content:space-around;">
          <div style="margin:5px;">
            <div style="font-size:14px;">
              <div style="text-align: center;font-size:16px;margin-bottom: 10px;">
                共{{ questionList.tableData.length }}题
              </div>
              <van-count-down v-if="singleQuestion.isJiShi" :time="4 * 60 * 60 * 1000" format="剩余答题时间 HH 时 mm 分 ss 秒 此处时间仅为模拟" />
            </div>
          </div>
        </div>
        <el-divider />
        <div v-for="(item, index) of questionList.tableData" :key="index" class="paper">
          <div class="paper-title">{{ index+1 }}、{{ item.TG }}（{{ item.FS }}分）</div>
          <!-- 配图 -->
          <div v-if="item.PT">
            <el-image style="width: 380px; margin:10px 10px 20px 50px;" :src="item.PT" fit="contain" />
          </div>
          <!-- 单选 -->
          <el-radio-group v-if="item.TMLX.search(/单选/i) !== -1" v-model="answerList[index]">
            <div v-if="item.XXA" class="paper-xuan-xiang">
              <el-radio label="A">A. {{ item.XXA }}</el-radio>
            </div>
            <div v-if="item.XXB" class="paper-xuan-xiang">
              <el-radio label="B">B. {{ item.XXB }}</el-radio>
            </div>
            <div v-if="item.XXC" class="paper-xuan-xiang">
              <el-radio label="C">C. {{ item.XXC }}</el-radio>
            </div>
            <div v-if="item.XXD" class="paper-xuan-xiang">
              <el-radio label="D">D. {{ item.XXD }}</el-radio>
            </div>
            <div v-if="item.XXE" class="paper-xuan-xiang">
              <el-radio label="E">E. {{ item.XXE }}</el-radio>
            </div>
            <div v-if="item.XXF" class="paper-xuan-xiang">
              <el-radio label="F">F. {{ item.XXF }}</el-radio>
            </div>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group v-if="item.TMLX.search(/多选/i) !== -1" v-model="answerList[index]">
            <div v-if="item.XXA" class="paper-xuan-xiang">
              <el-checkbox label="A">A. {{ item.XXA }}</el-checkbox>
            </div>
            <div v-if="item.XXB" class="paper-xuan-xiang">
              <el-checkbox label="B">B. {{ item.XXB }}</el-checkbox>
            </div>
            <div v-if="item.XXC" class="paper-xuan-xiang">
              <el-checkbox label="C">C. {{ item.XXC }}</el-checkbox>
            </div>
            <div v-if="item.XXD" class="paper-xuan-xiang">
              <el-checkbox label="D">D. {{ item.XXD }}</el-checkbox>
            </div>
            <div v-if="item.XXE" class="paper-xuan-xiang">
              <el-checkbox label="E">E. {{ item.XXE }}</el-checkbox>
            </div>
            <div v-if="item.XXF" class="paper-xuan-xiang">
              <el-checkbox label="F">F. {{ item.XXF }}</el-checkbox>
            </div>
          </el-checkbox-group>
          <!-- 填空 -->
          <div v-if="item.TMLX.search(/填空/i) !== -1" class="paper-tian-kong">
            <div>
              <el-input v-if="item.XXA" v-model="answerList[index]['A']" autosize maxlength="255" type="textarea" placeholder="在此填写第一个空" />
            </div>
            <div>
              <el-input v-if="item.XXB" v-model="answerList[index]['B']" autosize maxlength="255" type="textarea" placeholder="在此填写第二个空" />
            </div>
            <div>
              <el-input v-if="item.XXC" v-model="answerList[index]['C']" autosize maxlength="255" type="textarea" placeholder="在此填写第三个空" />
            </div>
            <div>
              <el-input v-if="item.XXD" v-model="answerList[index]['D']" autosize maxlength="255" type="textarea" placeholder="在此填写第四个空" />
            </div>
            <div>
              <el-input v-if="item.XXE" v-model="answerList[index]['E']" autosize maxlength="255" type="textarea" placeholder="在此填写第五个空" />
            </div>
            <div>
              <el-input v-if="item.XXF" v-model="answerList[index]['F']" autosize maxlength="255" type="textarea" placeholder="在此填写第六个空" />
            </div>
          </div>
          <!-- <div>
            {{item}}
          </div> -->
        </div>
      </div>
      <!-- 单题卷显示 -->
      <div v-if="questionList.DTMS === '单题'" class="stu-card">
        <div class="flex-row" style="justify-content:space-around;">
          <el-button :disabled="singleQuestion.canNotPrevious" style="margin:5px" type="primary" @click="onClickPrevious">
            上一题
          </el-button>
          <div style="margin:5px;">
            <div style="font-size:14px;">
              <div style="text-align: center;font-size:14px;margin-bottom: 5px;">
                第{{ singleQuestion.index+1 }}题（共{{ questionList.tableData.length }}题）
              </div>
              <van-count-down v-if="singleQuestion.isJiShi" :time="4 * 60 * 60 * 1000" format="剩余答题时间 HH 时 mm 分 ss 秒 此处时间仅为模拟" />
            </div>
          </div>
          <el-button style="margin:5px" type="primary" @click="onClickNext">
            下一题
          </el-button>
        </div>
        <el-divider />
        <div class="paper">
          <div class="paper-title">{{ singleQuestion.index+1 }}、{{ questionList.tableData[singleQuestion.index].TG }}（{{ questionList.tableData[singleQuestion.index].FS }}分）</div>
          <!-- 配图 -->
          <div v-if="questionList.tableData[singleQuestion.index].PT">
            <el-image style="width: 380px; margin:10px 10px 20px 50px;" :src="questionList.tableData[singleQuestion.index].PT" fit="contain" />
          </div>
          <!-- 单选 -->
          <el-radio-group v-if="questionList.tableData[singleQuestion.index].TMLX.search(/单选/i) !== -1" v-model="answerList[singleQuestion.index]">
            <div v-if="questionList.tableData[singleQuestion.index].XXA" class="paper-xuan-xiang">
              <el-radio label="A">A. {{ questionList.tableData[singleQuestion.index].XXA }}</el-radio>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXB" class="paper-xuan-xiang">
              <el-radio label="B">B. {{ questionList.tableData[singleQuestion.index].XXB }}</el-radio>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXC" class="paper-xuan-xiang">
              <el-radio label="C">C. {{ questionList.tableData[singleQuestion.index].XXC }}</el-radio>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXD" class="paper-xuan-xiang">
              <el-radio label="D">D. {{ questionList.tableData[singleQuestion.index].XXD }}</el-radio>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXE" class="paper-xuan-xiang">
              <el-radio label="E">E. {{ questionList.tableData[singleQuestion.index].XXE }}</el-radio>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXF" class="paper-xuan-xiang">
              <el-radio label="F">F. {{ questionList.tableData[singleQuestion.index].XXF }}</el-radio>
            </div>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group v-if="questionList.tableData[singleQuestion.index].TMLX.search(/多选/i) !== -1" v-model="answerList[singleQuestion.index]">
            <div v-if="questionList.tableData[singleQuestion.index].XXA" class="paper-xuan-xiang">
              <el-checkbox label="A">A. {{ questionList.tableData[singleQuestion.index].XXA }}</el-checkbox>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXB" class="paper-xuan-xiang">
              <el-checkbox label="B">B. {{ questionList.tableData[singleQuestion.index].XXB }}</el-checkbox>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXC" class="paper-xuan-xiang">
              <el-checkbox label="C">C. {{ questionList.tableData[singleQuestion.index].XXC }}</el-checkbox>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXD" class="paper-xuan-xiang">
              <el-checkbox label="D">D. {{ questionList.tableData[singleQuestion.index].XXD }}</el-checkbox>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXE" class="paper-xuan-xiang">
              <el-checkbox label="E">E. {{ questionList.tableData[singleQuestion.index].XXE }}</el-checkbox>
            </div>
            <div v-if="questionList.tableData[singleQuestion.index].XXF" class="paper-xuan-xiang">
              <el-checkbox label="F">F. {{ questionList.tableData[singleQuestion.index].XXF }}</el-checkbox>
            </div>
          </el-checkbox-group>
          <!-- 填空 -->
          <div v-if="questionList.tableData[singleQuestion.index].TMLX.search(/填空/i) !== -1" class="paper-tian-kong">
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXA" v-model="answerList[singleQuestion.index]['A']" autosize maxlength="255" type="textarea" placeholder="在此填写第一个空" />
            </div>
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXB" v-model="answerList[singleQuestion.index]['B']" autosize maxlength="255" type="textarea" placeholder="在此填写第二个空" />
            </div>
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXC" v-model="answerList[singleQuestion.index]['C']" autosize maxlength="255" type="textarea" placeholder="在此填写第三个空" />
            </div>
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXD" v-model="answerList[singleQuestion.index]['D']" autosize maxlength="255" type="textarea" placeholder="在此填写第四个空" />
            </div>
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXE" v-model="answerList[singleQuestion.index]['E']" autosize maxlength="255" type="textarea" placeholder="在此填写第五个空" />
            </div>
            <div>
              <el-input v-if="questionList.tableData[singleQuestion.index].XXF" v-model="answerList[singleQuestion.index]['F']" autosize maxlength="255" type="textarea" placeholder="在此填写第六个空" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- dialog 删除试卷 -->
    <div v-if="!isLoading">
      <el-dialog title="警告！" :visible.sync="showDialog.deletePaper" width="30%">
        <span>删除后无法恢复！你确定删除名为{{ paperList.selectedPaperName }}的试卷吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.deletePaper = false">取 消</el-button>
          <el-button type="primary" @click="onDeletePaper">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 导出文件对话框 -->
    <el-dialog title="导出到本地" :visible.sync="showDialog.downloadTableDialog">
      <div class="dialogForm">
        <FilenameOption v-model="downloadTable.filename" />
        <AutoWidthOption v-model="downloadTable.autoWidth" />
        <BookTypeOption v-model="downloadTable.bookType" />
        <div>
          <el-button :loading="downloadTable.downloadLoading" style="margin: 12px 0 0 0" type="primary" icon="el-icon-document" @click="handleDownload">
            导出表格
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 添加新行对话框 -->
    <el-dialog v-el-drag-dialog title="添加新行" :visible.sync="showDialog.addRowsDialog">
      <div class="dialogForm">
        <div v-if="showDialog.addRowsDialog" class="flex-row">
          <div v-for="(item, index) in addRows.rowArr " :key="item.title" style="height: 48px">
            <label class="radio-label" style="padding-left: 16px">{{ item.title }}：</label>
            <el-input v-model="addRows.rowArr[index].value" maxlength="255" style="width: 200px" placeholder="" />
          </div>
        </div>
        <div>

          <el-select v-model="addRows.selectValue" placeholder="请选择">
            <el-option v-for="(item, index) in addRows.selectOptions" :key="index" :label="item.label" :value="index" />
          </el-select>

          <el-input-number v-if="addRows.selectValue == 2" v-model="addRows.addWhere" :min="1" :max="updataPaper.tableData.length" />
          <el-button style="margin: 12px 20px 0 20px" type="primary" @click="addNewTableRows">
            添加新行
          </el-button>
          <el-button style="margin: 12px 20px 0 20px" type="warning" @click="cleanAddTableRowsForm">
            清空输入框
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 修改某一行对话框 -->
    <el-dialog :title="'正在修改：第'+(alterRows.selectRow+1)+'行'" :visible.sync="showDialog.alterRowsDialog">
      <div class="dialogForm">
        <div v-if="this.showDialog.alterRowsDialog" class="flex-row">
          <div v-for="(item, index) in alterRows.rowArr " :key="item.title" style="height: 48px">
            <label class="radio-label" style="padding-left: 16px">{{ item.title }}：</label>
            <el-input v-model="alterRows.rowArr[index].value" maxlength="255" style="width: 200px" placeholder="" />
          </div>
        </div>
        <div>
          <el-button style="margin: 12px 20px 0 20px" type="primary" @click="alterTableRows">
            更新此行
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 删除某一行 -->
    <el-dialog :title="'正在删除：第'+(alterRows.selectRow+1)+'行'" :visible.sync="showDialog.deleteRowsDialog">
      <div class="dialogForm">
        <div>请仔细核对原始数据，删除后无法恢复。</div>
        <div v-if="showDialog.deleteRowsDialog">{{ updataPaper.tableData[alterRows.selectRow] }}</div>
        <el-button style="margin: 12px 20px 0 20px" type="danger" @click="deleteTableRows">
          删除此行
        </el-button>
      </div>
    </el-dialog>
    <!-- 更新此试卷 -->
    <el-dialog title="正在将数据同步到数据库" :visible.sync="showDialog.updataMyPaper">
      <div class="dialogForm">
        <div>你确定更新此试卷？请仔细检查表格内容，此操作无法撤销！</div>
        <el-button style="margin: 12px 20px 0 20px" type="danger" @click="updataQuestionToDatabase">
          开始同步
        </el-button>
      </div>
    </el-dialog>
    <!-- ———————————— -->
  </div>
</template>

<script>
import waves from '@/directive/waves/index.js' // 水波纹指令
import elDragDialog from '@/directive/el-drag-dialog' // 可拖拽dialog
import { mapGetters } from 'vuex'

// options components
import FilenameOption from './components/FilenameOption'
import AutoWidthOption from './components/AutoWidthOption'
import BookTypeOption from './components/BookTypeOption'

// 引用API
import { updataQuestion, getPaper, deletePaper, getQuestion } from '@/api/paper'

// 引用插件
// import moment from 'moment'
// import CountDown from 'vue2-countdown';

export default {
  name: 'ManagePaper',
  components: {
    FilenameOption,
    AutoWidthOption,
    BookTypeOption
  },
  directives: {
    waves,
    elDragDialog
  },
  data() {
    return {
      updataPaper: {
        isShow: false,
        tableHeader: [{ prop: 'XH', label: '序号', width: '36' }, { prop: 'FS', label: '分数', width: '40' }, { prop: 'TG', label: '题干', width: '300' }, { prop: 'PT', label: '配图', width: '220' }, { prop: 'TMLX', label: '题目类型', width: '' }, { prop: 'ZQXX', label: '正确选项', width: '' }, { prop: 'XXA', label: '选项A', width: '' }, { prop: 'XXB', label: '选项B', width: '' }, { prop: 'XXC', label: '选项C', width: '' }, { prop: 'XXD', label: '选项D', width: '' }, { prop: 'XXE', label: '选项E', width: '' }, { prop: 'XXF', label: '选项F', width: '' }],
        tableData: [],
        paperName: '',
        paperAuthor: ''
      }, // 修改试卷
      showDialog: {
        deletePaper: false,
        downloadTableDialog: false,
        addRowsDialog: false,
        alterRowsDialog: false,
        deleteRowsDialog: false,
        updataMyPaper: false // 同步到数据库
      },
      isLoading: true,
      paperList: {
        isShow: true,
        onlyWatchMyself: true,
        tableData: [],
        selected: 0,
        selectedPaperName: ''
      },
      questionList: {
        isShow: false,
        tableData: [],
        DTMS: '整卷', // 答题模式
        ZJXS: '顺序', // 组卷形式 顺序或者随机
        paperName: '',
        paperAuthor: ''
      },
      singleQuestion: {
        isJiShi: true, // 启用计时
        canNotPrevious: true, // 不允许点击“上一题按钮”
        index: 0// 当前题目位置

      },
      alterRows: {
        rowJSON: {},
        rowArr: [],
        selectRow: undefined
      }, // 修改行
      addRows: {
        rowJSON: {},
        rowArr: [],
        selectOptions: [
          { label: '在开头' },
          { label: '在结尾' },
          { label: '指定行' }
        ], // 选择器选项
        selectValue: 0, // 选择器选择的插入位置 0:在开头，1：在结尾..。设置见selectOptions
        addWhere: 1 // 当选择器选择自定义插入位置时候，判定在哪里插入。注意，从1开始计数
      }, // 新增行
      downloadTable: {
        downloadLoading: false, // 正在下载
        filename: '', // 下载文件的文件名
        autoWidth: false, // 是否自动列宽
        bookType: 'xlsx' // 生成的格式
      }, // 下载文件
      answerList: []
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'roles'])

  },
  created: function() {
    this.onPostGetPaper()
  },
  mounted() {
  },
  methods: {
    /**
     * 更新题目到数据库
     */
    async updataQuestionToDatabase() {
      if (this.name !== this.updataPaper.paperAuthor) {
        this.$message({
          message: '你不能修改其他人创建的试卷！',
          type: 'warning'
        })
        return
      }
      this.resetIndexOfTable()
      try {
        this.isLoading = true
        const data = {
          tableData: this.updataPaper.tableData,
          paperName: this.updataPaper.paperName,
          paperAuthor: this.updataPaper.paperAuthor
        }
        const callback = await updataQuestion(data)
        this.$message({
          message: callback.data.message,
          type: callback.data.type
        })
        console.log(callback.data)
        this.isLoading = false
        this.showDialog.updataMyPaper = false
        this.updataPaper.isShow = false
        this.paperList.isShow = true
        // location.reload()
      } catch {
        this.isLoading = false
        return
      }
    },
    /**
     * 添加行前的初始化
     */
    beforeAddRow() {
      this.addRows.rowArr = []
      for (let i = 0; i < this.updataPaper.tableHeader.length; i++) {
        this.addRows.rowArr.push({ 'title': this.updataPaper.tableHeader[i].label, 'value': '' })
        this.addRows.rowJSON[this.updataPaper.tableHeader[i].prop] = ''
      }
      console.log('初始化addRow', this.addRows)
      this.showDialog.addRowsDialog = true
    },
    /**
     * 修改行前的初始化
     */
    beforAlterRow() {
      if (this.alterRows.selectRow === undefined) {
        this.$message({
          message: '你未选择任何行！',
          type: 'warning'
        })
        return false
      }
      this.alterRows.rowArr = []
      for (let i = 0; i < this.updataPaper.tableHeader.length; i++) {
        this.alterRows.rowArr.push({ 'title': this.updataPaper.tableHeader[i].label, 'value': this.updataPaper.tableData[this.alterRows.selectRow][this.updataPaper.tableHeader[i].prop] })
        this.alterRows.rowJSON[this.updataPaper.tableHeader[i].prop] = ''
      }
      console.log('初始化addRow', this.alterRows)
      this.showDialog.alterRowsDialog = true
    },
    /**
     * 更新此行
     */
    alterTableRows() {
      // console.log("您介是干嘛")
      let j = 0
      for (const i in this.alterRows.rowJSON) {
        this.alterRows.rowJSON[i] = this.alterRows.rowArr[j].value
        console.log(this.alterRows.rowJSON[i], '/', this.alterRows.rowArr[j].value)
        j++
      }
      console.log(this.alterRows.rowJSON)
      // this.updataPaper.tableData.splice(
      //   this.alterRows.selectRow,
      //   1,
      //   JSON.parse(JSON.stringify(this.alterRows.rowJSON))
      // )
      for (const i in this.alterRows.rowJSON) {
        this.updataPaper.tableData[this.alterRows.selectRow][i] = this.alterRows.rowJSON[i]
      }

      this.$message({
        message:
          '更新成功！更新位置：第 ' + (this.alterRows.selectRow + 1) + ' 行',
        type: 'success'
      })
    },
    /**
    * 删除某行
    */
    deleteTableRows() {
      if (this.alterRows.selectRow === undefined) {
        this.$message({
          message: '你未选择任何行！',
          type: 'warning'
        })
        return
      }
      if (this.updataPaper.tableData.length === 1) {
        this.$message({
          message:
            '哇哦！无法删除，因为表格不能为空',
          type: 'error'
        })
        return
      }
      this.updataPaper.tableData.splice(this.alterRows.selectRow, 1)
      this.$message({
        message:
          '删除成功！删除位置：第 ' + (this.alterRows.selectRow + 1) + ' 行',
        type: 'success'
      })
    },
    /**
     * 添加行时，清除输入框
     */
    cleanAddTableRowsForm() {
      let j = 0
      console.log('清除输入框')
      for (const i in this.addRows.rowJSON) {
        // this.$set(this.addRows.rowArr[j],'value','')
        console.log('addrows 值为', this.addRows.rowArr[j].value)
        this.addRows.rowArr[j].value = ''
        this.addRows.rowJSON[i] = ''
        j++
      }
    },
    /**
 * 添加新行
 */
    addNewTableRows() {
      let j = 0
      for (const i in this.addRows.rowJSON) {
        this.addRows.rowJSON[i] = this.addRows.rowArr[j].value
        j++
      }
      if (this.addRows.selectValue === 0) {
        this.updataPaper.tableData.unshift(
          JSON.parse(JSON.stringify(this.addRows.rowJSON))
        )
        this.$message({
          message:
            '添加成功！插入位置：' +
            (this.addRows.selectValue === 0
              ? '开头'
              : '哇哦，意料之外的情况出现了！'),
          type: 'success'
        })
      }
      if (this.addRows.selectValue === 1) {
        this.updataPaper.tableData.push(
          JSON.parse(JSON.stringify(this.addRows.rowJSON))
        )
        this.$message({
          message:
            '添加成功！插入位置：' +
            (this.addRows.selectValue === 1
              ? '结尾'
              : '哇哦，意料之外的情况出现了！'),
          type: 'success'
        })
      }
      if (this.addRows.selectValue === 2) {
        this.updataPaper.tableData.splice(
          this.addRows.addWhere - 1,
          0,
          JSON.parse(JSON.stringify(this.addRows.rowJSON))
        )
        this.$message({
          message:
            '添加成功！插入位置：第 ' +
            (this.addRows.selectValue === 2
              ? this.addRows.addWhere
              : '哇哦，意料之外的情况出现了！') +
            ' 行',
          type: 'success'
        })
      }
    },
    /**
         * 点击上一题
         */
    onClickPrevious() {
      if (this.singleQuestion.index-- <= 0) this.singleQuestion.index++
    },
    /**
     * 点击下一题
     */
    onClickNext() {
      if (!this.questionCheck()) return
      if (this.singleQuestion.index++ >= this.questionList.tableData.length - 1) this.singleQuestion.index--
    },
    /**
     * 题目检查，主要用来在不允许点击上一步的时候，判断用户是否做完当题
     */
    questionCheck() {
      if (this.singleQuestion.canNotPrevious === true) {
        console.log('没用的console')
      }
      return true
    },
    /**
     * 题目显示初始化，主要用来随机化试卷题目
     */
    questionInit() {
      // await this.onGetQuestion()
      if (this.questionList.ZJXS === '乱序') {
        console.log('打乱了')
        this.$set(this.questionList.tableData, this.shuffle(this.questionList.tableData))
      } else {
        console.log('去数据库重新拉了')
        this.onGetQuestion()
      }
    },
    /**
     * 洗牌算法
     */
    shuffle(arr) {
      for (let i = arr.length - 1; i >= 0; i--) {
        const rIndex = Math.floor(Math.random() * (i + 1))
        // 打印交换值
        // console.log(i, rIndex);
        const temp = arr[rIndex]
        arr[rIndex] = arr[i]
        arr[i] = temp
      }
      return arr
    },

    /**
     * 对比2个对象是否相同
     */
    isTheTwoArrAreSame(j1, j2) {
      // console.log(JSON.stringify(j1))
      // console.log(JSON.stringify(j2))
      if (JSON.stringify(j1) === JSON.stringify(j2)) return true
      return false
    },
    /**
     * API: 获取paper列表
     *
     */
    async onPostGetPaper() {
      try {
        this.isLoading = true
        this.paperList.isShow = false

        const callback = await getPaper()
        this.isLoading = false
        this.paperList.isShow = true
        if (this.paperList.onlyWatchMyself === true) {
          this.paperList.tableData = []
          for (let i = 0; i < callback.data.length; i++) {
            if (callback.data[i]['paper_author'] === this.name) this.paperList.tableData.push(callback.data[i])
          }
          return
        }
        this.paperList.tableData = callback.data
        // console.log(callback.data)
      } catch {
        this.isLoading = false
        return
      }
    },
    /**
     * API: 获取question列表
     */
    async onGetQuestion() {
      try {
        this.isLoading = true
        const data = {
          paperName: this.questionList.paperName,
          paperAuthor: this.questionList.paperAuthor
        }
        const callback = await getQuestion(data)
        this.isLoading = false
        this.questionList.tableData = callback.data
        this.updataPaper.tableData = JSON.parse(JSON.stringify(callback.data))
        this.answerList = []
        for (let i = 0; i < callback.data.length; i++) {
          if (callback.data[i]['TMLX'] === '填空' || callback.data[i]['TMLX'] === '简答') {
            this.answerList.push({})
            if (callback.data[i]['XXA']) this.$set(this.answerList[i], 'A', '')
            if (callback.data[i]['XXB']) this.$set(this.answerList[i], 'B', '')
            if (callback.data[i]['XXC']) this.$set(this.answerList[i], 'C', '')
            if (callback.data[i]['XXD']) this.$set(this.answerList[i], 'D', '')
            if (callback.data[i]['XXE']) this.$set(this.answerList[i], 'E', '')
            if (callback.data[i]['XXF']) this.$set(this.answerList[i], 'F', '')
            continue
          }
          this.answerList.push([])
        }
        // console.log(callback.data)
      } catch {
        this.isLoading = false
        return
      }
    },
    /**
     *  API: 获取question列表
     *  和question分来
     */
    async onGetUpdataPaper() {
      try {
        this.isLoading = true
        const data = {
          paperName: this.updataPaper.paperName,
          paperAuthor: this.updataPaper.paperAuthor
        }
        const callback = await getQuestion(data)
        this.isLoading = false
        this.updataPaper.tableData = JSON.parse(JSON.stringify(callback.data))
        this.answerList = []
        for (let i = 0; i < callback.data.length; i++) {
          if (callback.data[i]['TMLX'] === '填空' || callback.data[i]['TMLX'] === '简答') {
            this.answerList.push({})
            if (callback.data[i]['XXA']) this.$set(this.answerList[i], 'A', '')
            if (callback.data[i]['XXB']) this.$set(this.answerList[i], 'B', '')
            if (callback.data[i]['XXC']) this.$set(this.answerList[i], 'C', '')
            if (callback.data[i]['XXD']) this.$set(this.answerList[i], 'D', '')
            if (callback.data[i]['XXE']) this.$set(this.answerList[i], 'E', '')
            if (callback.data[i]['XXF']) this.$set(this.answerList[i], 'F', '')
            continue
          }
          this.answerList.push([])
        }
        // console.log(callback.data)
      } catch {
        this.isLoading = false
        return
      }
    },
    /**
     * 点击查看试卷详情
     */
    onhandlePaperClick(row) {
      this.paperList.isShow = false
      this.questionList.isShow = true
      this.paperList.selectedPaperName = []
      // console.log('点击的row是', row)
      for (let i = 0; i < this.paperList.tableData.length; i++) {
        if (this.isTheTwoArrAreSame(this.paperList.tableData[i], row)) {
          this.paperList.selected = i
          this.paperList.selectedPaperName = this.paperList.tableData[i]['paper_name']
          break
        }
      }
      this.questionList.paperName = this.paperList.tableData[this.paperList.selected]['paper_name']
      this.questionList.paperAuthor = this.paperList.tableData[this.paperList.selected]['paper_author']
      this.onGetQuestion()
      // console.log("index是", this.paperList.selected)
      // console.log(index)
    },
    /**
     * 点击修改试卷
     */
    onhandleUpdataClick(row) {
      this.paperList.isShow = false
      this.updataPaper.isShow = true
      this.paperList.selectedPaperName = []
      for (let i = 0; i < this.paperList.tableData.length; i++) {
        if (this.isTheTwoArrAreSame(this.paperList.tableData[i], row)) {
          this.paperList.selected = i
          this.paperList.selectedPaperName = this.paperList.tableData[i]['paper_name']
          break
        }
      }
      this.updataPaper.paperName = this.paperList.tableData[this.paperList.selected]['paper_name']
      this.updataPaper.paperAuthor = this.paperList.tableData[this.paperList.selected]['paper_author']
      this.onGetUpdataPaper()
    },
    /**
     * 检查正在删除的试卷是否属于登录者
     */
    checkOnDelete(row) {
      for (let i = 0; i < this.paperList.tableData.length; i++) {
        if (this.isTheTwoArrAreSame(this.paperList.tableData[i], row)) {
          this.paperList.selected = i
          this.paperList.selectedPaperName = this.paperList.tableData[i]['paper_name']
          break
        }
      }
      if (this.paperList.tableData[this.paperList.selected]['paper_author'] !== this.name) {
        this.$message({
          message: '你不能删除其他人创建的试卷！',
          type: 'error'
        })
        return
      }
      this.showDialog.deletePaper = true
    },
    /**
     * 删除该试卷
     */
    async onDeletePaper() {
      try {
        this.isLoading = true
        const data = {
          paperName: this.paperList.tableData[this.paperList.selected]['paper_name'],
          paperAuthor: this.paperList.tableData[this.paperList.selected]['paper_author'],
          operator: this.name
        }
        const callback = await deletePaper(data)

        this.isLoading = false
        this.showDialog.deletePaper = false
        this.paperList.tableData = callback.data
        this.paperList.selected = 0 // 这里有风险，如果删除最后一个的话，下标如果不变，会越过边界指向undefined。暂时设为0解决。（设为0时也有bug。如果是删除第0个，之后也会越界。）___胡说八道 邹超2021年5月16日 22:50:54
        // console.log(callback)
        this.$message({
          message: callback.data.message,
          type: callback.data.type
        })

        this.onPostGetPaper()
      } catch (err) {
        console.error(err.message)
        this.isLoading = false
        return
      }
    },
    /**
     * 返回上一页
     */
    goBack() {
      this.paperList.isShow = true
      this.questionList.isShow = false
      this.updataPaper.isShow = false
    },
    /**
     * 给table每格rows加上属性
     */
    tableRowClassName({ row, rowIndex }) {
      row.row_index = rowIndex
    },
    /**
     * 点击了某一行
     */
    onRowClick(row, event, column) {
      this.alterRows.selectRow = row.row_index
      // console.log(row.row_index)
    },
    /**
     * 重整序号
     */
    resetIndexOfTable() {
      for (let i = 0; i < this.updataPaper.tableData.length; i++) {
        this.updataPaper.tableData[i]['XH'] = (i + 1).toString()
      }
      this.$message({
        message:
          '重整序号成功',
        type: 'success'
      })
      return true
    },
    /**
     * 开始下载文件，导出表格
     */
    handleDownload() {
      this.downloadTable.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tmepHead = []
        const tmepHeadLabel = []
        for (let i = 0; i < this.updataPaper.tableHeader.length; i++) {
          tmepHead.push(this.updataPaper.tableHeader[i].prop)
          tmepHeadLabel.push(this.updataPaper.tableHeader[i].label)
        }
        console.log(tmepHead)
        const filterVal = tmepHead
        const list = this.updataPaper.tableData
        const data = this.formatJson(filterVal, list)
        console.log(data)
        excel.export_json_to_excel({
          header: tmepHeadLabel, // 表头 必填
          data,
          filename: this.downloadTable.filename,
          autoWidth: this.downloadTable.autoWidth,
          bookType: this.downloadTable.bookType
        })
        this.downloadTable.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          // console.log("测试",j,"/",v[j]);
          return v[j]
        })
      )
    }
  }
}

</script>

<style scoped>
.stu-card {
  padding: 24px;
  margin: 0 auto 10px auto;
  max-width: 1080px;
  background-color: #fff;
}

.my-container {
  padding: 10px 10px 60px 10px;
  background-color: #e6e6e6;
  min-height: calc(100vh - 84px);
}
.my-card {
  padding: 24px;
  margin-bottom: 10px;
  background-color: #fff;
}
.flex-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  min-height: 26px;
}
.paper {
  font-size: 18px;
  line-height: 200%;
  padding-bottom: 34px;
  width: 720px;
}

.paper-title {
  padding-bottom: 10px;
}

.paper-xuan-xiang {
  padding-left: 36px;
  padding-bottom: 10px;
}

.paper-tian-kong > * {
  width: 520px;
  margin: 0 0 5px 30px;
}

.flex-column-center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>

<style>
.paper-xuan-xiang .el-radio,
.paper-xuan-xiang .el-radio__label,
.paper-xuan-xiang .el-checkbox,
.paper-xuan-xiang .el-checkbox__label {
  font-size: 16px !important;
  line-height: 200%;
  color: #000;
}
</style>
